package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author Ahmad
 * @date 2024/12/20 23:35
 * @description
 * 自定义的类型转换器工厂类
 *利用多态，使得类型转换的转换范围更大，可以转换任意枚举类型
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()) {//获取枚举常量
                    if (enumConstant.getCode().toString().equals(source)) {//枚举常量对应的code与前端传来的字符串相等
                        return enumConstant;
                    }
                }
                return null;
            }
        };
    }
}